﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace MusicDatabase
{
    /*
     * Auteur:  Joris Molnár en Niels van Leusden
     * Datum:   31-1-2013
     * Omschrijving: Deze Klasse maakt het mogelijk om albums toe te kunnen voegen aan de database.
     *               Echter niet direct, deze klasse spreekt vooral de klasse Album aan.
     *               Voert vanuit de klasse AddSong de daadwerkelijke methode voor het toevoegen van een song uit.
     *               En maakt het ook mogelijk toegevoegde songs weer te verwijderen.
     *               Laat de gebruiker een foto kiezen om als cover toe te voegen aan het album, en slaat deze dan ook netjes op.
     *               De Klasse bevat ook een methode die bepaalt wanneer het formulier gesloten kan en mag worden.
     *               En slaat tot slot daadwerkelijk het nieuwe album op in de database.          
     *                          
     * 
     */
    public partial class AddAlbum : Form
    {
        private string coverImage = "";
        private int albumID;
        private bool newAlbum;
        private string price;
        private string year;

        /// <summary>
        /// Add album
        /// </summary>
        public AddAlbum()
        {
            InitializeComponent();
            newAlbum = true;
            albumID = -1;

            FillDgv();
        }

        /// <summary>
        /// Edit album
        /// </summary>
        /// <param name="albumID"></param>
        public AddAlbum(int albumID)
        {
            InitializeComponent();

            btnAddSong.Enabled = true;

            this.albumID = albumID;
            newAlbum = false;

            FillFields(albumID);
            FillDgv();
        }

        /// <summary>
        /// Fill the form with existing information
        /// </summary>
        /// <param name="albumID"></param>
        private void FillFields(int albumID)
        {
            Album album = new Album();
            string[] albumData = album.GetAlbum(albumID);
            tbAlbum.Text = albumData[1];
            tbPrice.Text = albumData[3];
            tbYear.Text = albumData[2];
            coverImage = "-1";
            if (albumData[4] != "")
            {
                try
                {
                    using (FileStream fs = new FileStream(@".\Covers\" + albumData[4], FileMode.Open, FileAccess.Read))
                    {
                        pbPreview.Image = Image.FromStream(fs);
                    }
                }
                catch (FileNotFoundException ex)
                {
                    MessageBox.Show("The following file was not found: \r\n\r\n" + ex.FileName);
                    album.AddCover("", albumID);
                }
                //pbPreview.Image = Image.FromFile(@".\Covers\" + albumData[4]);
                btnClear.Enabled = true;
            }
        }

        /// <summary>
        /// Fill the DGV
        /// </summary>
        private void FillDgv()
        {
            SQLServices sqlService = new SQLServices();
            string command = "SELECT song.song_id, songrelease.song_alb_track Nr, song.song_name Title, artist.art_name Artist, genre.genre_name Genre, CONVERT(nvarchar, song.song_length/60) + ':' + CASE WHEN song.song_length%60<10 THEN '0' + CONVERT(nvarchar, song.song_length%60) ELSE CONVERT(nvarchar, song.song_length%60) END Lengte, song.song_date Jaar " +
                "FROM song LEFT OUTER JOIN genre ON genre.genre_id = song.song_genre, songrelease, artist " +
                "WHERE songrelease.song_id = song.song_id AND song.art_id = artist.art_id AND songrelease.alb_id = " + albumID + " " +
                "ORDER BY songrelease.song_alb_track";
            List<string[]> songTable = sqlService.GetTable(command);

            dgvSongs.Columns.Clear();
            for (int i = 0; i < songTable[0].Length; i++) // Fill the DGV
            {
                dgvSongs.Columns.Add(songTable[0][i], songTable[0][i]);
            }
            for (int i = 1; i < songTable.Count; i++)
            {
                dgvSongs.Rows.Add(songTable[i]);
            }
            dgvSongs.Columns[0].Visible = false; // Make song_id invisible

            dgvSongs.Columns[1].Width = 25;
            dgvSongs.Columns[2].Width = 150;
            dgvSongs.Columns[3].Width = 89;
            dgvSongs.Columns[4].Width = 50;
            dgvSongs.Columns[5].Width = 50;
            dgvSongs.Columns[6].Width = 40;

        }

        private void btnAddSong_Click(object sender, EventArgs e)
        {
            AddSong addsong = new AddSong();
            btnAddSong.Enabled = false;

            addsong.ShowDialog();

            if (addsong.DialogResult == DialogResult.OK)
            {
                string[] songData = addsong.SongData;

                Song song = new Song(songData);
                song.Save(albumID);

                AlbumArtist();
                FillDgv();
            }

            btnAddSong.Enabled = true;
        }

        /// <summary>
        /// Set the albumartist as various artist if more then one worked on an album
        /// </summary>
        private void AlbumArtist()
        {
            int artistID;
            SQLServices sqlService = new SQLServices();
            
            //string command = "SELECT song.art_id " +
            //    "FROM song, songrelease " +
            //    "WHERE song.song_id = songrelease.song_id " +
            //    "GROUP BY song.alb_id";

            string command = "SELECT DISTINCT song.art_id " +
                "FROM song, songrelease " +
                "WHERE song.song_id = songrelease.song_id AND songrelease.alb_id = " + albumID;
            List<string[]> artistTable = sqlService.GetTable(command);

            if (artistTable.Count == 2) // One Artist
            {
                artistID = Convert.ToInt32(artistTable[1][0]);
            }
            else // Multiple artist (Various Artist)
            {
                artistID = 21; // Dit was artistID 1, maar vanwege een probleempje met autonummering, moet het nu 21 zijn...
            }

            // Update de ALBUM tabel.
            command = "UPDATE album SET alb_artist = " + artistID + " WHERE alb_id = " + albumID;
            sqlService.Update(command);

        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (ofdAlbumCover.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            coverImage = ofdAlbumCover.FileName;
            try
            {
                using (FileStream fs = new FileStream(coverImage, FileMode.Open, FileAccess.Read))
                {
                    pbPreview.Image = Image.FromStream(fs);
                }
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show("The following file was not found: \r\n\r\n" + ex.FileName);
            }
            tbPath.Text = coverImage;
            btnClear.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            #region Inputcheck
            if (tbAlbum.Text.Trim() == "")
            {
                MessageBox.Show("No album name was given.");
                return;
            }

            if (tbYear.Text.Trim() == "")
            {
                MessageBox.Show("No release year was given.");
                return;
            }

            try
            {
                // Make price work with both a comma and a period and see if they will work later
                price = Convert.ToString(double.Parse(tbPrice.Text.Trim().Replace('.', ','), System.Globalization.CultureInfo.GetCultureInfo("nl-NL")), System.Globalization.CultureInfo.InvariantCulture);
                year = Convert.ToString(Convert.ToInt32(tbYear.Text.Trim()));
            }
            catch (FormatException)
            {
                price = "0";
                year = "0";
                MessageBox.Show("Something went wrong with the input. Please check everything later.");
            }
            #endregion

            if (newAlbum) // New Album
            {
                if (AlbumExist())
                {
                    MessageBox.Show("This album already exist.");
                    return;
                }

                Album album = new Album(new string[] { tbAlbum.Text.Trim(), "", price, "", year });
                album.Save();
                this.albumID = album.AlbumID;

                if (coverImage != "")
                {
                    string imageName = albumID + Path.GetExtension(coverImage).ToLower();
                    File.Copy(coverImage, @".\Covers\" + imageName, true);
                    album.AddCover(imageName, albumID);
                }

                btnAddSong.Enabled = true;
                newAlbum = false;
            }
            else // Edit Album
            {
                SQLServices sqlService = new SQLServices();
                Album album = new Album();
                string command = "UPDATE album SET alb_name = '" + tbAlbum.Text.Trim().Replace("'", "''") + "', alb_price = '" + price + "', alb_date = '" + year + "' WHERE alb_id = " + albumID;

                sqlService.Update(command);

                if (coverImage == "")
                {
                    album.AddCover("", albumID);
                }
                else if (coverImage != "-1")
                {
                    string imageName = albumID + Path.GetExtension(coverImage).ToLower();
                    File.Copy(coverImage, @".\Covers\" + imageName, true);
                    album.AddCover(imageName, albumID);
                }
            }
        }

        /// <summary>
        /// Look if an album already exist
        /// </summary>
        /// <returns></returns>
        private bool AlbumExist()
        {
            Album album = new Album();
            return album.Exist(tbAlbum.Text.Trim(), year);
        }

        private void AddAlbum_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CanClose()) // Prevent the form from closing
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// If there are no songs in an album, prevent this form from closing
        /// </summary>
        /// <returns></returns>
        private bool CanClose()
        {
            SQLServices sqlService = new SQLServices();
            string command = "SELECT COUNT(song_id) FROM songrelease WHERE alb_id = " + albumID;
            if (Convert.ToInt32(sqlService.GetTable(command)[1][0]) <= 0 && albumID != -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            btnClear.Enabled = false;
            tbPath.Text = "";
            coverImage = "";
            pbPreview.Image = null;
        }

        private void btnDeleteSong_Click(object sender, EventArgs e)
        {
            DialogResult dialogresult = MessageBox.Show("Are you sure you want to delete the selected songs?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (dialogresult == DialogResult.Yes)
            {
                List<int> songID = new List<int>(); // Get the selected rows from the cells
                foreach (DataGridViewCell cell in dgvSongs.SelectedCells)
                {
                    songID.Add(Convert.ToInt32(dgvSongs.Rows[cell.RowIndex].Cells[0].FormattedValue));
                }
                songID = new HashSet<int>(songID).ToList<int>();

                Song song = new Song();
                song.DeleteSongs(songID);

                AlbumArtist();
                FillDgv();
            }
            else
            {
                return;
            }
        }
    }
}
